<template>
  <a-modal
    title="新增"
    :width="1500"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          label="名称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-input placeholder="请输入名称" v-decorator="['title', {rules: [{required: true, message: '请输入名称！'}]}]" />
        </a-form-item>
        <a-form-item
          label="图片地址"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-upload
            :customRequest="customRequest"
            :multiple="true"
            :showUploadList="false"
            name="file"
          >
            <a-button>
              <a-icon type="upload"/>
              <span v-if="imageId > 0">重新上传</span>
              <span v-else>上传图片</span>
            </a-button>
            <img v-if="imageId > 0" :src="imageUrl" style="width:150px">
          </a-upload>
        </a-form-item>
      </a-form>
      <!--    内容    -->
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="内容"
      >
        <antd-editor :uploadConfig="editorUploadConfig" v-model="editorContent" @onchange="changeEditor" @oninit="getEditor" />
      </a-form-item>
    </a-spin>
  </a-modal>
</template>

<script>
  import { appBannerAdd } from '@/api/modular/app/banner/appBannerManage'
  import { sysFileInfoUploadFront } from '@/api/modular/system/fileManage'
  import { AntdEditor } from '@/components'
  export default {
    name: 'AddForm',
    components: {
      AntdEditor
    },
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        // 文件
        fileBucket: 'banner',
        userId: '1', // 用户id
        // 图片赋值
        oldImageId: '', // 旧头像id
        imageId: '',
        imageUrl: '',
        // 编辑器
        editorContent: '',
        editorContentText: '',
        editorUploadConfig: {
          method: 'http',
          callback: this.editorUploadImage
        }
      }
    },
    methods: {
      /**
       * 编辑器回调上传及回传图片url
       */
      editorUploadImage (files, insert) {
        const formData = new FormData()
        files.forEach(file => {
          formData.append('file', file)
          formData.append('fileBucket', this.fileBucket)
          formData.append('userId', this.userId)
        })
        sysFileInfoUploadFront(formData).then((res) => {
          if (res.success) {
            insert(process.env.VUE_APP_API_BASE_URL + '/sysFileInfo/preview?id=' + res.data.filedId)
          } else {
            this.$message.error('编辑器上传图片失败：' + res.message)
          }
        })
      },
      getEditor (editor) {
        this.editor = editor
      },
      changeEditor (html, ele) {
        this.editorContent = html
        this.editorContentText = ele.text()
      },
      // 初始化方法
      add (record) {
        this.visible = true
      },
      /**
       * 提交表单
       */
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            for (const key in values) {
              if (typeof (values[key]) === 'object' && values[key] != null) {
                values[key] = JSON.stringify(values[key])
              }
            }
            // 判断是否有上传新头像 有赋值
            if (this.imageId !== this.oldImageId) {
              values.imageId = this.imageId
            }
            values.message = this.editorContent
            appBannerAdd(values).then((res) => {
              if (res.success) {
                this.$message.success('新增成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error('新增失败')// + res.message
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
      },
      /**
       * 上传文件
       */
      customRequest(data) {
        const formData = new FormData()
        formData.append('file', data.file)
        formData.append('fileBucket', this.fileBucket)
        formData.append('userId', this.userId)
        sysFileInfoUploadFront(formData).then((res) => {
          if (res.success) {
            // 赋值到headPicId headPicUrl字段
            this.imageId = res.data.filedId
            this.imageUrl = res.data.sysFileInfo
            this.$message.success('上传成功')
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        })
      }
    }
  }
</script>
